<template>
  <div class="tinymce-editor">
    <editor v-if="visibile" v-model="value" :init="init" />
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/wordcount'
export default {
  // name: 'tinymce-editor',
  props: {
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    visibile: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    value(val) {
      if (this.flag) {
        tinymce.activeEditor && tinymce.activeEditor.setContent(val)
      }
      this.flag = true
    }
  },
  components: {
    Editor
  },
  data() {
    const component = this
    return {
      flag: true,
      init: {
        language_url: '/static/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/static/tinymce/skins/ui/oxide',
        height: 430,
        plugins: 'link lists image code table wordcount',
        toolbar: 'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat',
        branding: false,
        images_upload_handler: function (blobInfo, success, failure) {
          var file = blobInfo.blob()

          var reader = new FileReader()

          reader.readAsDataURL(file)

          reader.onloadend = function () {
            if (file.size > 1048576) {
              failure('图片请不要大于 1MB')
            } else {
              success(reader.result)
            }
          }
        },
        setup: function(editor) {
          editor.on('input undo redo execCommand', function(e) {
            component.flag = false
            component.$emit('input', editor.getContent())
          })
        }

      }
    }
  },
  mounted() {
    tinymce.init({})
  },
  methods: {
    clear() {
      this.html = ''
    }
  }
}
</script>

<style lang="stylus">
  // 修复弹出框不显示下拉框问题
  // https://segmentfault.com/q/1010000019136840?utm_source=tag-newest
  .tox-silver-sink
    z-index 3000!important
</style>
